package com.wujilin.okra.loader;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.database.Cursor;

public abstract class CursorLoader extends AsyncTaskLoader<Cursor> {
	private Cursor cursor;
	
	public CursorLoader(Context context) {
		super(context);
	}
	
	/**
	 * Load the cursor on a worker thread.
	 * 
	 * @return The Cursor for loading
	 */
	public abstract Cursor loadCursor();

	@Override
	public Cursor loadInBackground() {
		Cursor cursor = loadCursor();
		if (cursor != null) {
			cursor.getCount();
		}
		return cursor;
	}
	
	@Override
	public void deliverResult(Cursor cursor) {
		Cursor oldCursor = this.cursor;
		this.cursor = cursor;
		if (isStarted()) {
			super.deliverResult(cursor);
		}
        if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
            oldCursor.close();
        }
	}
	
	@Override
	protected void onStartLoading() {
		if (cursor != null) {
			deliverResult(cursor);
		}
		if (takeContentChanged() || cursor == null) {
			forceLoad();
		}
	}
	
	@Override
	protected void onStopLoading() {
		cancelLoad();
	}
	
	@Override
	public void onCanceled(Cursor cursor) {
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
	}
	
	@Override
	protected void onReset() {
		super.onReset();
		onStopLoading();
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		cursor = null;
	}
}
